﻿#ifndef __MUTEX_H__
#define __MUTEX_H__
#include "Common.h"

namespace sky
{
    // 互斥量
    class SKY_EXPORT Mutex
    {
        CRITICAL_SECTION m_cs;
    #ifdef SKY_DEBUG
        const char *    file;
        int             line;
    #endif

    public:
        Mutex(bool = true);
        ~Mutex();
    
    #ifdef SKY_DEBUG
        void Lock(const char * f = 0, int l = 0);
        void UnLock();
    #else
        void Lock();
        void UnLock();
    #endif
    };

    //信号量
    class SKY_EXPORT Semaphore
    {
        void * m_h;
    
    public:
        Semaphore(int initCount = 0);
        ~Semaphore();

        bool Wait(unsigned long timeOut = 0xFFFFFFFF);
        void Post();
    };

    // 守卫
    // 临界区线程安全自动保护
    template<class _Mutex = Mutex>
    class ResGuard
    {
        _Mutex mMutex;
    public:
        ResGuard(_Mutex& mtx):mMutex(mtx)
        {
            mMutex.Lock();
        }

        ~ResGuard()
        {
            mMutex.UnLock();
        }
    };



    typedef ResGuard<Mutex>     scopelock;

} // namespace sky

#endif